//
//  JYUserAccountViewModel.swift
//  01.weibo
//
//  Created by 谢玉锋 on 16/7/12.
//  Copyright © 2016年 itheima.cn. All rights reserved.
//

import UIKit

class JYUserAccountViewModel: NSObject {

    static let sharaInstance = JYUserAccountViewModel()
    private override init() {
        super.init()
        userAccount = loadUserAccount()
    }
    
    var userAccount: JYUserAccount?
    var userlogin: Bool {
        get{
        return userAccount != nil
        }
    }

    //申请网络请求:
    //因为闭包错误不一定会返回错误,所以为可选
    func posdAccessToken (code:String , loadAccountCallBack: (error: NSError?) -> ()) {
        
        let parameters = [
            "client_id":client_id,
            "client_secret":client_secret,
            "grant_type":grant_type,
            "code":code,
            "redirect_uri":redirect_uri
        ]
        JYNetworkTool.shareInstance.POST(accessTokenURLString, parameters: parameters, progress: nil, success: { (task, responseObject) -> Void in
            //当授权成功之后,在登录时,不会再来而去直接获取accessToken,除非,取消授权
//            JYPrint("成功: \(responseobject)")
            //字典转模型
            let result = responseObject as? [String: AnyObject]
            //选择绑定                                                                      ???
            if let dict = result {
                
                //调用这个方法存档
                self.userAccount = JYUserAccount(dict: dict)
//                JYPrint(self.userAccount)
                //保存账号
                self.saveUserAccount()
                
                //保存账号成功之后--> 应该通知控制器
                loadAccountCallBack(error: nil)
                
            }
            
            }) { (task, error) -> Void in
                JYPrint("失败: \(error)")
                loadAccountCallBack(error: error)
        }
    }
    
    // MARK: - 获取用户信息   先定义闭包( 获取成功或失败时可以获取数据 )    提示闭包写法!!!
    func loadUserInfo (loadUserIfocallback: (error: NSError?) -> ()) {
    
        //URLString
        let urlString = "https://api.weibo.com/2/users/show.json"

        
        guard let access_token = self.userAccount?.access_token else {
            // domain: 自定义: 表示错误范围
            // code: 自定义: 表示错误类型,一般是以负数开头
            // userInfo: 附加的信息
            
            let error = HMNetworkErrorEnum.AccessTokenEmpty.error()
            loadUserIfocallback(error: error)
            
        return
        }
        guard let uid = self.userAccount?.uid else {
        let error = HMNetworkErrorEnum.UidEmpty.error()
            loadUserIfocallback(error: error)
        return
        }
        
    //参数
        let parameters = [
            "access_token" : access_token,
            "uid" : uid
        ]
    //发送请求:
        JYNetworkTool.shareInstance.GET(urlString, parameters: parameters, progress: nil, success: { (task, responseObject) -> Void in
//            JYPrint("加载用户信息成功:\(responseObject)")
                if let dict = responseObject as? [String: AnyObject] {
                self.userAccount?.screen_name = dict["screen_name"] as? String
                self.userAccount?.avatar_large = dict["avatar_large"] as? String
                //// 将当前对象保存到沙盒中
                self.saveUserAccount()
                    //调用闭包
                loadUserIfocallback(error: nil)
            }
            }) { (task, error) -> Void in
                //调用闭包
                loadUserIfocallback(error: error)
        }
    }
  
    //归档
    private func saveUserAccount () {
        //归档
        //可选绑定
        if let userAccount = self.userAccount {
            //这里直接强制拆包比较危险,如果拿不到数据,就蹦,所有用可选绑定比较好
            NSKeyedArchiver.archiveRootObject(userAccount, toFile: accountPath)
        
        }
    }
    
    //解档
    func loadUserAccount () -> JYUserAccount? {
    
        let userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? JYUserAccount

//        userAccount?.expires_inDate? = NSDate(timeIntervalSinceNow: -10000) 测试是否过期能否过期
        if let account = userAccount where userAccount?.expires_inDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending{
//            JYPrint("没过期: \(account)")
        return account
        }
        // 返回值为 -> JYUserAccount?  时才可以返回nil
        return nil
    }
    
}






